document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('post-demand-form');
    const successMessage = document.getElementById('success-message');
    
    // 表单验证函数
    function validateForm() {
        let isValid = true;
        
        // 验证标题
        const title = document.getElementById('title');
        if (!title.value.trim()) {
            document.getElementById('title-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('title-error').style.display = 'none';
        }
        
        // 验证需求类型
        const demandType = document.getElementById('demand-type');
        if (!demandType.value) {
            document.getElementById('demand-type-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('demand-type-error').style.display = 'none';
        }
        
        // 验证学校名称
        const schoolName = document.getElementById('school-name');
        if (!schoolName.value.trim()) {
            document.getElementById('school-name-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('school-name-error').style.display = 'none';
        }
        
        // 验证学校类型
        const schoolType = document.getElementById('school-type');
        if (!schoolType.value) {
            document.getElementById('school-type-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('school-type-error').style.display = 'none';
        }
        
        // 验证省份
        const province = document.getElementById('province');
        if (!province.value) {
            document.getElementById('province-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('province-error').style.display = 'none';
        }
        
        // 验证城市
        const city = document.getElementById('city');
        if (!city.value.trim()) {
            document.getElementById('city-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('city-error').style.display = 'none';
        }
        
        // 验证地址
        const address = document.getElementById('address');
        if (!address.value.trim()) {
            document.getElementById('address-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('address-error').style.display = 'none';
        }
        
        // 验证开始日期
        const startDate = document.getElementById('start-date');
        if (!startDate.value) {
            document.getElementById('start-date-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('start-date-error').style.display = 'none';
        }
        
        // 验证结束日期
        const endDate = document.getElementById('end-date');
        if (!endDate.value) {
            document.getElementById('end-date-error').style.display = 'block';
            isValid = false;
        } else if (new Date(endDate.value) <= new Date(startDate.value)) {
            document.getElementById('end-date-error').textContent = '结束日期必须晚于开始日期';
            document.getElementById('end-date-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('end-date-error').style.display = 'none';
        }
        
        // 验证科目选择
        const subjects = document.querySelectorAll('input[name="subjects[]"]:checked');
        if (subjects.length === 0) {
            document.getElementById('subjects-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('subjects-error').style.display = 'none';
        }
        
        // 验证需求人数
        const peopleCount = document.getElementById('people-count');
        if (!peopleCount.value || peopleCount.value < 1) {
            document.getElementById('people-count-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('people-count-error').style.display = 'none';
        }
        
        // 验证需求描述
        const description = document.getElementById('description');
        if (!description.value.trim()) {
            document.getElementById('description-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('description-error').style.display = 'none';
        }
        
        // 验证联系人姓名
        const contactName = document.getElementById('contact-name');
        if (!contactName.value.trim()) {
            document.getElementById('contact-name-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('contact-name-error').style.display = 'none';
        }
        
        // 验证联系电话
        const contactPhone = document.getElementById('contact-phone');
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!contactPhone.value.trim()) {
            document.getElementById('contact-phone-error').textContent = '请输入联系电话';
            document.getElementById('contact-phone-error').style.display = 'block';
            isValid = false;
        } else if (!phoneRegex.test(contactPhone.value.trim())) {
            document.getElementById('contact-phone-error').textContent = '请输入有效的手机号码';
            document.getElementById('contact-phone-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('contact-phone-error').style.display = 'none';
        }
        
        // 验证电子邮箱（如果填写）
        const contactEmail = document.getElementById('contact-email');
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        if (contactEmail.value.trim() && !emailRegex.test(contactEmail.value.trim())) {
            document.getElementById('contact-email-error').style.display = 'block';
            isValid = false;
        } else {
            document.getElementById('contact-email-error').style.display = 'none';
        }
        
        return isValid;
    }
    
    // 表单提交处理
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        
        // 验证表单
        if (validateForm()) {
            // 检查用户是否已登录
            const isLoggedIn = checkLoginStatus(); // 这个函数需要在实际环境中实现
            
            if (isLoggedIn) {
                // 模拟表单提交
                submitForm();
            } else {
                // 提示用户登录
                alert('请先登录后再提交支教需求');
                window.location.href = 'login.html?redirect=post-demand.html';
            }
        } else {
            // 滚动到第一个错误处
            const firstError = document.querySelector('.form-error[style="display: block"]');
            if (firstError) {
                firstError.parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
            }
        }
    });
    
    // 模拟检查登录状态
    function checkLoginStatus() {
        // 这里应该是实际检查用户是否登录的代码
        // 为了演示，我们假设用户已登录
        return true;
    }
    
    // 模拟表单提交
    function submitForm() {
        // 显示加载状态
        const submitButton = form.querySelector('.btn-submit');
        const originalText = submitButton.textContent;
        submitButton.textContent = '提交中...';
        submitButton.disabled = true;
        
        // 模拟API请求延迟
        setTimeout(function() {
            // 隐藏表单，显示成功消息
            form.style.display = 'none';
            successMessage.style.display = 'block';
            
            // 滚动到成功消息
            successMessage.scrollIntoView({ behavior: 'smooth', block: 'center' });
            
            // 重置按钮状态
            submitButton.textContent = originalText;
            submitButton.disabled = false;
            
            // 在实际应用中，这里应该是发送表单数据到服务器的代码
            console.log('表单提交成功');
        }, 1500);
    }
    
    // 日期验证 - 设置最小日期为今天
    const today = new Date().toISOString().split('T')[0];
    document.getElementById('start-date').min = today;
    document.getElementById('end-date').min = today;
    
    // 开始日期变化时更新结束日期的最小值
    document.getElementById('start-date').addEventListener('change', function() {
        document.getElementById('end-date').min = this.value;
    });
});